package com.lam.common.base.domain;

import com.lam.common.exception.BaseException;
import com.lam.common.utils.StringUtils;

/**
 * 操作消息提醒
 * 
 * @author lam
 */
public class Result  {
	
	/** 状态码 */
	protected int code = MsgCode.FAIL.getCode();
	/** 返回消息提示 */
	protected String msg;
	/** 数据对象 */
	protected Object data;

	public Result() {}

    public Result(BaseException e) {
        setCode(e.getCode());
        setMsg(e.getMsg());
    }
    
    public Result(MsgCode msgCode) {
        this.code = msgCode.getCode();
        this.msg = msgCode.getMsg();
    }

    public static Result ok(){
    	return Result.isSuccess(true);
    }
    
    public static Result ok(String msg){
    	return Result.ok().msg(msg);
    }
    
    public static Result ok(Object data){
    	return Result.ok().data(data);
    }
    
    public static Result fail(){
    	return Result.isSuccess(false);
    }
    
    public static Result fail(String msg){
    	return Result.fail().msg(msg);
    }
    
    public static Result fail(BaseException e){
    	return new Result(e).setSuccess(false);
    }
    
    public static Result fail(MsgCode msgCode){
    	return new Result(msgCode).setSuccess(false);
    }
    
    private static Result isSuccess(boolean success){
    	return new Result().setSuccess(success);
    }
    
    public Result data(Object data) {
    	setData(data);
        return this;
    }

    public Result code(int code) {
        setCode(code);
        return this;
    }

    public Result msg(String msg) {
        setMsg(msg);
        return this;
    }
    
    public boolean isSuccess(){
    	return getCode() == MsgCode.SUCCESS.getCode();
    }
    
    public Result setSuccess(boolean success){
    	if (success){
    		setCode(MsgCode.SUCCESS.getCode());
    		setMsg(StringUtils.isBlank(msg)? MsgCode.SUCCESS.getMsg() :msg);
        }else{
        	setCode(code == 0||code == MsgCode.SUCCESS.getCode() ? MsgCode.FAIL.getCode() : code);
        	setMsg(StringUtils.isBlank(msg)? MsgCode.FAIL.getMsg() :msg);
        }
    	return this;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }
    
    public String getMessage() {
    	return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

}
